﻿using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;

namespace AntUnion.FrameWork.Web.Extend
{
    /// <summary>
    /// 小程序相关帮助类
    /// </summary>
    public class MiniProgramHelper
    {
        /// <summary>
        /// 根据code返回openid、session_key
        /// </summary>
        /// <param name="context"></param>
        /// <param name="appid">小程序 appId</param>
        /// <param name="appsecret">小程序 appSecret</param>
        /// <param name="js_code">登录时获取的 code</param>
        /// <returns></returns>
        public static Jscode2session GetJscode2session(mtContext context, string appid, string appsecret, string js_code)
        {
            try
            {
                string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={appsecret}&js_code={js_code}&grant_type=authorization_code";
                string data = HttpUtil.HttpGet(url);
                //LogHelper.ErrorLog("ex", data, "UserController", "GetJscode2session", "CB");
                Jscode2session jscode2session = data.ToObject<Jscode2session>();
                //bool isRegister = context.Members.Any(k => k.RoutineOpenid == jscode2session.openId);
                //jscode2session.IsRegister = isRegister;
                return jscode2session;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static string GetPhoneNumber(WxPhoneNumber wxPhoneNumber, string appid, string appsecret)
        {
            try
            {
                Jscode2session jscode2session = GetJscode2session(null,appid, appsecret, wxPhoneNumber.js_code);
                //请求成功
                if (jscode2session.errcode != 0)
                {
                    throw new Exception(jscode2session.errmsg);
                }
                string phone = GetPhoneNumber(wxPhoneNumber.encryptedData, wxPhoneNumber.iv, jscode2session.session_key);
                return phone;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private static string GetPhoneNumber(string encryptedData, string iv, string session_key)
        {
            try
            {
                byte[] encryData = Convert.FromBase64String(encryptedData);
                RijndaelManaged rijndaelCipher = new RijndaelManaged
                {
                    Key = Convert.FromBase64String(session_key),
                    IV = Convert.FromBase64String(iv),
                    Mode = CipherMode.CBC,
                    Padding = PaddingMode.PKCS7
                };
                ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
                string result = Encoding.Default.GetString(plainText);
                dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
                return model.phoneNumber;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        ///获取小程序全局唯一后台接口调用凭据
        /// </summary>
        /// <param name="appid">小程序 appId</param>
        /// <param name="appsecret">小程序 appSecret</param>
        /// <returns></returns>
        public static AccessToken GetAccessToken(string appid, string appsecret)
        {
            try
            {
                string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}";
                string data = HttpUtil.HttpGet(url);
                AccessToken accessToken = data.ToObject<AccessToken>();
                if (accessToken.errcode == 0)
                {
                    return accessToken;
                }
                else
                {
                    throw new Exception(accessToken.errmsg);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 根据code返回openid、session_key
        /// </summary>
        /// <param name="appid">小程序 appId</param>
        /// <param name="appsecret">小程序 appSecret</param>
        /// <param name="js_code">登录时获取的 code</param>
        /// <returns></returns>
        public static Stream GetUnlimited(string token, string scene)
        {
            try
            {
                string url = $"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={token}";
                UnlimitedQRCodeModel qrcodeModel = new UnlimitedQRCodeModel
                {
                    scene = scene
                };
                string json = qrcodeModel.ToJson();
                Stream stream = HttpUtil.HttpPost2Steram(url, json);
                return stream;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
